package com.hb.medical_research_system.service.impl;

import com.hb.medical_research_system.common.Results;
import com.hb.medical_research_system.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${medical.path}")
    private String BasePath;

    public Results upload(MultipartFile file) {
        //file是一个临时文件,需要转存到指定位置,否则本次请求完成后,临时文件会自动删除
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名称,防止文件名重复
        String fileName = UUID.randomUUID() + suffix;

        //创建一个目录对象
        File dir = new File(BasePath);
        if(!dir.exists()){
            //若目录不存在,在创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(BasePath + fileName));
        } catch (IOException e) {

        }
        return Results.data(Results.SUCCESS, fileName, "文件上传成功");
    }

    public Results download(String name, HttpServletResponse response){
        try {
            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(BasePath+name));

            //输出流,通过输出流将文件写回浏览器, 在浏览器显示图片
            ServletOutputStream servletOutputStream = response.getOutputStream();

            //设置回去的文件类型
            response.setContentType("application/pdf");

            int len = 0;
            byte[] bytes = new byte[1024];
            while((len = fileInputStream.read(bytes))!=-1){
                servletOutputStream.write(bytes,0,len);
                servletOutputStream.flush();
            }
//            servletOutputStream.write();
            //关闭资源
            servletOutputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Results.info(Results.SUCCESS,"下载成功");
    }
}
